<?php

namespace App\Repositories;


use App\Models\Code;
use App\Models\CodeValue;
use App\Utils\Output;
use App\Utils\Pager;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class CodeRepository
 * @package App\Repositories
 */
class CodeRepository
{
    static $codeMap = [];

    function getMap($code)
    {
        if (isset(self::$codeMap[$code])) {
            return self::$codeMap[$code];
        }
        $lis = CodeValue::query()->where('code', '=', $code)->select('name', 'value')->get();
        $map = array();
        foreach ($lis as $li) {
            $map[$li->value] = $li->name;
        }
        self::$codeMap[$code] = $map;
        return $map;
    }
    function adminPager($params)
    {
        extract($params);
        $query = Code::query();
        if (!empty($keyword)) {
            $query->where(function (Builder $q) use ($keyword) {
                $q->orWhere('name', 'like', "%$keyword%");
                $q->orWhere('code', 'like', "%$keyword%");
            });
        }
        $query->select('id', 'name', 'code', 'desc', 'updated_at');
        return $query->paginate();
    }

    function editInfo($id)
    {
        $entity = Code::find($id);
        if ($entity) {
            return Output::data($entity);
        }
        return Output::fail("数据不存在");
    }

    function save($data, $id)
    {
        return Code::store($data, $id);
    }

    /**
     * 删除
     * @param $id
     * @return Output|int
     * @throws \Exception
     */
    function destroy($id)
    {
        return Code::destroy($id);
    }
}

